import Cookies from 'js-cookie'
// cookie保存的天数
import config from '@/config'

import { objEqual } from '@/libs/tools'

export const TOKEN_KEY = 'token'

export const setToken = (token) => {
    const date = new Date(new Date().getTime() + 60 * 60 * 1000 * config.cookieExpires)
    Cookies.set(TOKEN_KEY, token, { expires: date })
}

export const getToken = () => {
    const token = Cookies.get(TOKEN_KEY)
    if (token) return token
    else return false
}

// 设置游客身份cookie
const IS_VISITOR = 'ROTISIV'
export const setVisitorStatus = (value) => {
    value === '1' ? Cookies.set(IS_VISITOR, '1') : Cookies.remove(IS_VISITOR)
}
export function getVisitorStatus () {
    return Cookies.get(IS_VISITOR) === '1'
}

// 记住密码的用户数据
const LOGIN_SERIALIZ_ABLE = 'ELBAZILAIRES'

// 清空所有本地存储
export function clearAllStorage () {
    const lginSerializ = getLoginSerializ()
    window.localStorage.clear()
    window.sessionStorage.clear()
    // 记住密码的用户数据不能清理，需要重新保存
    lginSerializ.length && window.localStorage.setItem(LOGIN_SERIALIZ_ABLE, JSON.stringify(lginSerializ))
}

// 检查记住密码是否过期
function checkLoginSerializExpired (data, days = 7) {
    return data.t && (new Date().getTime() - data.t <= 86400000 * days)
}

/**
 * 获取所有7天记住登录的客户
 * @return {Array} 数据数组
 */
export function getLoginSerializ () {
    let data = JSON.parse(window.localStorage.getItem(LOGIN_SERIALIZ_ABLE))
    if (Object.prototype.toString.call(data) !== '[object Array]') data = []
    return data
}

/**
 * 获取7天记住登录的用户
 * @param {String} key 用户名
 * @return {String} loginSerializable值
 */
export function getLoginSerializByKey (key) {
    let data = getLoginSerializ()
    const index = data.findIndex(item => item.u === key)
    if (index < 0) return ''
    if (checkLoginSerializExpired(data[index])) {
        return data[index].v
    }
    // 过期则删除数据
    data.splice(index, 1)
    data.length
        ? window.localStorage.setItem(LOGIN_SERIALIZ_ABLE, JSON.stringify(data))
        : window.localStorage.removeItem(LOGIN_SERIALIZ_ABLE)
    return ''
}

/**
 * 设置7天记住登录的用户
 * @param {String} key 用户名
 * @param {String} value 值
 */
export function setLoginSerializByKey (key, value) {
    let data = getLoginSerializ()
    let index = data.findIndex(item => item.u === key)
    let info = data[index] || ''
    // 删除旧数据
    index > -1 && data.splice(index, 1)
    // 如果没有记录或者已经过期则设置新数据
    if (info === '' || !checkLoginSerializExpired(info)) {
        info = { u: key, v: value, t: +new Date() }
    } else {
        info.v = value
    }
    // 如果value有值则新数据添加到最前面
    value && data.unshift(info)
    // 最多存储10个用户
    data.length > 1 && data.pop()
    data.length
        ? window.localStorage.setItem(LOGIN_SERIALIZ_ABLE, JSON.stringify(data))
        : window.localStorage.removeItem(LOGIN_SERIALIZ_ABLE)
}

/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
// export const getBreadCrumbList = (routeMetched, homeRoute) => {
//   let res = routeMetched.filter(item => {
//     return item.meta === undefined || !item.meta.hide
//   }).map(item => {
//     let obj = {
//       icon: (item.meta && item.meta.icon) || '',
//       name: item.name,
//       meta: item.meta
//     }
//     return obj
//   })
//   res = res.filter(item => {
//     return !item.meta.hideInMenu
//   })
//   return [Object.assign(homeRoute, { to: homeRoute.path }), ...res]
// }

// 显示顶部导航栏title
export const showTitle = (item) => {
    return (item.meta && item.meta.title) || item.name
}

/**
 * @description 本地存储和获取标签导航列表
 */
export const setTagNavListInLocalstorage = list => {
    localStorage.tagNaveList = JSON.stringify(list)
}
/**
 * @returns {Array} 其中的每个元素只包含路由原信息中的name, path, meta三项
 */
export const getTagNavListFromLocalstorage = () => {
    const list = localStorage.tagNaveList
    return list ? JSON.parse(list) : []
}

// 首页名称
export let homeName = 'home'

export function setHomeName (name) {
    homeName = name
}

/**
 * @param {Array} routers 路由列表数组
 * @description 用于找到路由列表中name为home的对象
 */
export const getHomeRoute = routers => {
    let i = -1
    let len = routers.length
    let homeRoute = {}
    while (++i < len) {
        let item = routers[i]
        if (item.children && item.children.length) {
            let res = getHomeRoute(item.children)
            if (res.name) return res
        } else {
            if (item.name === homeName) homeRoute = item
        }
    }
    return homeRoute
}

/**
 * 根据角色权限获取首页route
 * @param {Array} permission 菜单列表
 * @param {String} role 角色信息
 * @param {Array} routes 路由信息
 */
export function getHomeRouteByRole (rolePermission, routes) {
    const target = getFirstRoute(rolePermission)
    console.log(target)
    target && setHomeName(target.name || homeName)
    return getHomeRoute(routes)

    function getFirstRoute (permission) {
        const route = permission[0]
        if (!route) return null
        if (route.children && route.children.length > 0) {
            return getFirstRoute(route.children)
        }
        return route
    }
}

/**
 * @param {*} list 现有标签导航列表
 * @param {*} newRoute 新添加的路由原信息对象
 * @description 如果该newRoute已经存在则不再添加
 */
export const getNewTagList = (list, newRoute) => {
    const { name, path, meta, params, query, fullPath } = newRoute
    const tagList = list.slice()
    var index = tagList.findIndex(item => item.name === name)

    const route = { name, path, params, query, fullPath, meta }
    // 如果是首页 不存在则添加
    if (name === homeName) {
        if (index < 0) tagList.unshift(route)
    } else {
    // 如果已存在删除再push 新增直接push
        index > -1
            ? tagList.splice(index, 1, route)
            : tagList.push(route)
    }
    return tagList
}

/**
 * @param {Array} list 标签列表
 * @param {String} name 当前关闭的标签的name
 */
export const getNextRoute = (list, route) => {
    let res = {}
    if (list.length === 2) {
        res = getHomeRoute(list)
    } else {
        const index = list.findIndex(item => routeEqual(item, route))
        if (index === list.length - 1) res = list[list.length - 2]
        else res = list[index + 1]
    }
    return res
}

/**
 * @param {Number} times 回调函数需要执行的次数
 * @param {Function} callback 回调函数
 */
export const doCustomTimes = (times, callback) => {
    let i = -1
    while (++i < times) {
        callback(i)
    }
}

/**
 * @param {Object} file 从上传组件得到的文件对象
 * @returns {Promise} resolve参数是解析后的二维数组
 * @description 从Csv文件中解析出表格，解析成二维数组
 */
export const getArrayFromFile = (file) => {
    let nameSplit = file.name.split('.')
    let format = nameSplit[nameSplit.length - 1]
    return new Promise((resolve, reject) => {
        let reader = new FileReader()
        reader.readAsText(file) // 以文本格式读取
        let arr = []
        reader.onload = function (evt) {
            let data = evt.target.result // 读到的数据
            let pasteData = data.trim()
            arr = pasteData.split((/[\n\u0085\u2028\u2029]|\r\n?/g)).map(row => {
                return row.split('\t')
            }).map(item => {
                return item[0].split(',')
            })
            if (format === 'csv') resolve(arr)
            else reject(new Error('[Format Error]:你上传的不是Csv文件'))
        }
    })
}

/**
 * @param {Array} array 表格数据二维数组
 * @returns {Object} { columns, tableData }
 * @description 从二维数组中获取表头和表格数据，将第一行作为表头，用于在iView的表格中展示数据
 */
export const getTableDataFromArray = (array) => {
    let columns = []
    let tableData = []
    if (array.length > 1) {
        let titles = array.shift()
        columns = titles.map(item => {
            return {
                title: item,
                key: item
            }
        })
        tableData = array.map(item => {
            let res = {}
            item.forEach((col, i) => {
                res[titles[i]] = col
            })
            return res
        })
    }
    return {
        columns,
        tableData
    }
}

/**
 * @description 根据name/params/query判断两个路由对象是否相等
 * @param {*} route1 路由对象
 * @param {*} route2 路由对象
 */
export const routeEqual = (route1, route2) => {
    // debugger;
    const params1 = route1.params || {}
    const params2 = route2.params || {}
    const query1 = route1.query || {}
    const query2 = route2.query || {}
    return (route1.name === route2.name) && objEqual(params1, params2) && objEqual(query1, query2)
}

/**
 * 判断打开的标签列表里是否已存在这个新添加的路由对象
 */
export const routeHasExist = (tagNavList, routeItem) => {
    let len = tagNavList.length
    let res = false
    doCustomTimes(len, (index) => {
        if (routeEqual(tagNavList[index], routeItem)) res = true
    })
    return res
}

/**
 * 日期转换
 */
export const changeData = (date, fmt) => {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length))
        }
    }
    return fmt
}
